var MsiComm = {
  //初始执行一次
  init: function() {
    // 侧边栏显示隐藏
    MsiComm.asideInit();
    // 广告位轮播
    MsiComm.locatSwiper();
    //根据时间自动设置比赛阶段以切换时间轴高亮
    MsiComm.autoSetTimeline();
    //各种动画
    // MsiComm.doAnimation('.txt-make-history', 'vanishIn', 1000);
    MsiComm.doAnimation(".slogan-kv-txt", "vanishEnter", 1000);
    // MsiComm.doAnimation('.txt-make-history', 'vanishIn', 1000);
    MsiComm.doAnimation(".slogan-logo", "flipInY", 1000);
    MsiComm.doAnimation(".slogan-txt", "flipInX", 1600, function() {
      $(".slogan-shape").addClass("anim");
      MsiComm.doAnimation(".slogan-address-timeline", "fadeInUp");
      MsiComm.doAnimation(".m-partner", "fadeInUp");
      MsiComm.doAnimation(".m-link", "fadeInUp");
    });
    //加载队伍列表
    // MsiComm.loadTeamList();
    //解说swiper
    MsiComm.initCommentatorSwiper();
    //现场花絮swiper
    MsiComm.initTitbitsAd();
    //比赛阶段切换
    // MsiComm.bindTab('.stage-type a', '.stage-panel');
    //英雄排行榜切换
    MsiComm.bindTab(".champion-rank-type a", ".rank-table-content-ul");
    //个人排行榜切换
    MsiComm.bindTab(".player-rank-type a", ".rank-tab-pr");
    //绑定各种切换效果
    MsiComm.bindSwitchElement(".mv-vod .vod-type a", "on");
    MsiComm.bindSwitchElement(".mv-vod .vod-stage-type a", "on");
    //MsiComm.bindSwitchElement('.m-match-video .video-type a','on');
    MsiComm.bindSwitchElement(".mv-schedule-type a", "on");
    MsiComm.bindSwitchElement(".mv-schedule-date a", "on");
    //视频点播 赛事回顾 绑定切换展开效果
    $(".mv-vod-list .vs-tag a").click(function() {
      $(".mv-vod-list .vs-tag a").removeClass("on");
      $(this).addClass("on");

      var $li = $(this)
        .parents(".vod-hd")
        .parent();
      $li
        .addClass("cur")
        .siblings()
        .removeClass("cur");
      MsiComm.bindVodSwiper();
    });
    //冠军左右滑动
    var championSwiper = new Swiper(".m-champion-team-container", {
      noSwiping: true
    });
    $(".m-champion-team-table li").click(function() {
      $(this)
        .addClass("selected")
        .siblings()
        .removeClass("selected");
      championSwiper.swipeTo($(this).index());
    });
    //视频直播加载
    //MsiComm.loadTxPlayer('r0018hmh1pa','liveCon',false);
  },
  //根据时间自动设置比赛阶段以切换时间轴高亮
  autoSetTimeline: function() {
    //根据日期激活活动入口
    var oDate = new Date(json_curdate.replace(/-/g, "/"));
    // var oDate = new Date('2018/05/07 10:00:00');
    var oDay = oDate.getDate();
    var oMonth = oDate.getMonth() + 1;
    var oYear = oDate.getFullYear();
    oDay = oDay < 10 ? "0" + oDay : "" + oDay;
    oMonth = oMonth < 10 ? "0" + oMonth : "" + oMonth;
    var curTime = parseInt(oYear + oMonth + oDay);

    var len = MsiComm.stageDate.length;
    for (var i = 0; i < len; i++) {
      var curStageDate = parseInt(MsiComm.stageDate[i]);
      if (curTime < curStageDate) {
        MsiComm.setTimeline(i);
        break;
      }
    }
  },
  //比赛阶段
  stageDate: [20190509, 20190517, 20991231],
  //比赛地址
  stageAddress: ["入围赛：德国 柏林", "小组赛：德国 柏林", "淘汰赛：法国 巴黎"],
  //设置比赛阶段
  setTimeline: function(index) {
    $(".timeline li")
      .eq(index)
      .addClass("on")
      .siblings()
      .removeClass();
    $(".m-kv .address").text(MsiComm.stageAddress[index]);
  },
  //初始化swiper
  initSwiper: function(data) {
    //根据容器和参数初始化swiper
    var tempSwiper = new Swiper(data.el, data["param"] || {});

    //是否有其他绑定执行参数
    data["otherFunc"] && data.otherFunc(tempSwiper);

    //初始化完成,返回
    return tempSwiper;
  },
  //解说swiper
  initCommentatorSwiper: function() {
    var swiperParam = {
      el: ".js-commentator-swiper-container",
      param: {
        onSlideChangeEnd: function(swiper) {
          MsiComm.checkRemain(swiper);
        }
      },
      otherFunc: function(swiper) {
        //绑定两个方向按钮的事件,并将其jQuery存入swiper,并且判断一次是否有剩余页
        swiper["leftBtn"] = $(".js-commentator-swiper-btn-left");
        swiper["rightBtn"] = $(".js-commentator-swiper-btn-right");

        swiper.leftBtn.on("click", function() {
          swiper.swipeTo(swiper.activeIndex - 1, 500);
        });

        swiper.rightBtn.on("click", function() {
          swiper.swipeTo(swiper.activeIndex + 1, 500);
        });

        MsiComm.checkRemain(swiper);
      }
    };
    MsiComm.initSwiper(swiperParam);
  },
  //判断是否还有下一页,并处理左右按钮的样式
  checkRemain: function(swiper) {
    var tempLeft = swiper.leftBtn;
    var tempRight = swiper.rightBtn;

    swiper.activeIndex === 0
      ? tempLeft.removeClass("remain")
      : tempLeft.addClass("remain");

    swiper.activeIndex === swiper.slides.length - 1
      ? tempRight.removeClass("remain")
      : tempRight.addClass("remain");
  },
  //现场花絮swiper
  initTitbitsAd: function() {
    //初始化现场图集的swiper
    var sceneSwiperOriginLength = $(".m-scene-swiper-wrapper").find("li")
      .length;
    var sceneSwiperParam = {
      el: ".m-scene-swiper-container",
      param: {
        slidesPerView: 3,
        watchActiveIndex: true,
        loop: true,
        offsetPxBefore: 413,
        simulateTouch: false,
        loopAdditionalSlides: 1
      },
      otherFunc: function(swiper) {
        //绑定两个方向按钮的事件,并将其和wrap的jQuery存入swiper,并且判断一次是否有剩余页
        swiper["leftBtn"] = $(".u-scene-btn-left").addClass("remain");
        swiper["rightBtn"] = $(".u-scene-btn-right").addClass("remain");

        swiper["wrap"] = $(".m-scene-swiper-wrapper");
        swiper["originLength"] = sceneSwiperOriginLength;

        swiper.leftBtn.on("click", function() {
          console.log(swiper.activeLoopIndex, swiper.originLength - 1);
          if (swiper.activeLoopIndex === swiper.originLength - 1) {
            //为了实现无缝衔接,在移到轮播图首的时候,瞬间移到轮播图尾巴去,再执行一次正常的移动.
            swiper.wrap.find("li").removeClass("anma");
            swiper.swipeTo(swiper.originLength - 1, 0);
            swiper.wrap.find("li").addClass("anma");
            setTimeout(function() {
              swiper.swipeTo(swiper.activeLoopIndex - 1, 500);
            });
          } else {
            swiper.swipeTo(swiper.activeLoopIndex - 1, 500);
          }
        });

        swiper.rightBtn.on("click", function() {
          swiper.swipeNext();
        });

        MsiComm.checkRemain(swiper);

        swiper.wrap.find("li").addClass("anma");
      }
    };
    MsiComm.initSwiper(sceneSwiperParam);
  },
  //绑定点击选中效果
  bindTab: function(head, content) {
    var selClass = "on";
    $(head)
      .off("click")
      .on("click", function() {
        if ($(this).hasClass(selClass)) return;
        $(this)
          .addClass(selClass)
          .siblings()
          .removeClass(selClass);
        $(content)
          .hide()
          .eq($(this).index())
          .fadeIn();
      });
  },
  //绑定点击选中效果
  bindSwitchElement: function(elm, selectedClassName) {
    var selClass = selectedClassName ? selectedClassName : "on";
    $(elm)
      .off("click")
      .on("click", function() {
        $(this)
          .addClass(selClass)
          .siblings()
          .removeClass(selClass);
      });
  },
  //执行动画
  doAnimation: function(elm, x, delay, callback) {
    if (delay) {
      setTimeout(function() {
        _doAnim();
      }, delay);
    } else {
      _doAnim();
    }

    function _doAnim() {
      $(elm).removeClass("animation-hide");
      $(elm)
        .removeClass(x + " animated")
        .addClass(x + " animated")
        .one(
          "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",
          function() {
            $(this).removeClass(x + " animated");
            if (typeof callback === "function") callback($(elm));
          }
        );
    }
  },
  //切聊天室/赛程按钮换动画是否完成
  switchBtnAnimationFinished: true,
  //聊天室/赛程按钮事件
  switchBtnAction: function() {
    if (!MsiComm.switchBtnAnimationFinished) return;
    var $btn = $(".main-video .btn-switch");
    var $schedule = $(".mv-schedule");
    var $chat = $(".mv-chat");
    var $redDot = $(".mv-chat-red-dot");
    MsiComm.switchBtnAnimationFinished = false;
    if ($schedule.css("display") === "block") {
      $btn.find("span").text("赛程");
      $schedule.animate(
        {
          height: 0
        },
        function() {
          $(this).hide();
          MsiComm.switchBtnAnimationFinished = true;
        }
      );
      $chat
        .show()
        .css({
          height: 0
        })
        .animate({
          height: "497px"
        });
      $redDot.hide();
    } else {
      $btn.find("span").text("聊天室");
      $chat.animate(
        {
          height: 0
        },
        function() {
          $(this).hide();
          MsiComm.switchBtnAnimationFinished = true;
        }
      );
      $schedule
        .show()
        .css({
          height: 0
        })
        .animate({
          height: "497px"
        });
      $redDot.show();
    }
  },
  //视频点播 swiper对象
  vodSwiper: null,
  //视频点播 绑定左右滚动组件
  bindVodSwiper: function() {
    if (MsiComm.vodSwiper) {
      MsiComm.vodSwiper.destroy(true);
      MsiComm.vodSwiper = null;
    }
    MsiComm.vodSwiper = new Swiper(".mv-vod-list li.cur .vod-bd-container", {
      slidesPerView: 3
    });
    $(".vod-left")
      .off("click")
      .click(function() {
        MsiComm.vodSwiper.swipePrev();
      });
    $(".vod-right")
      .off("click")
      .click(function() {
        MsiComm.vodSwiper.swipeNext();
      });
  },
  //回到顶部
  backToTop: function() {
    $("html,body")
      .stop()
      .animate(
        {
          scrollTop: 0
        },
        500
      );
  },
  //延迟加载竞猜iframe
  delayLoadGuessIframe: function() {
    $("#anchor05").html(
      '<iframe width="1180" height="366" frameborder="0" scrolling="no" src="https://qs.888.qq.com/m_qq/es/es.lol.html?channelName=liveIframe&active=msi2018#es.lol=init"></iframe>'
    );
  },
  //加载队伍列表
  loadTeamList: function() {
    var length = TeamData.length;
    var pagesize = 14;
    var page = Math.ceil(length / pagesize);
    var sHtml = "";
    for (var i = 0; i < page; i++) {
      var start = i * pagesize;
      var end = start + pagesize;
      if (end > length) {
        end = length;
      }
      sHtml += '<ul class="swiper-slide clearfix">';
      for (var x = start; x < end; x++) {
        var team = TeamData[x];
        sHtml +=
          '<li class="m-team-li"><a href="' +
          team.url +
          '" target="_blank"  class="u-team-logo"><img src="' +
          team.imgsrc +
          '" alt="战队logo"></a><p>' +
          team.areaTeam +
          "</p></li>";
      }
      sHtml += "</ul>";
    }
    $("#game_team").html(sHtml);
  },
  //广告位轮播
  locatSwiper: function() {
    var mySwiperLocat = new Swiper(".swiper-locat", {
      autoplay: 3000, //可选选项，自动滑动
      autoplayDisableOnInteraction: false,
      loop: true //可选选项，开启循环
    });
  },
  // 侧边栏
  asideInit: function() {
    $(window).on("scroll resize", function() {
      var $aside = $(".g-aside");
      var scrollTop = $(window).scrollTop();
      var clientWidth = document.body.clientWidth;
      if (scrollTop < 500 || clientWidth < 1462) {
        $aside.fadeOut(300);
      } else {
        $aside.fadeIn(300);
      }
    });
  },
  //弹窗
  dialog: {
    maskId: "__cimi_dialog_mask",
    curTarget: null,
    show: function(elmId) {
      var target = document.getElementById(elmId),
        that = this;

      var maskElm = document.createElement("div");
      maskElm.id = that.maskId;
      maskElm.style.cssText =
        "position:fixed;top:0;left:0;background: #000;width:100%;height:100%;z-index:9998;opacity: 0.7;filter:alpha(opacity=70)";

      if (that.curTarget) {
        that.curTarget.removeAttribute("style");
        that.curTarget.style.cssText = "display:none";
      }
      if (!document.getElementById(that.maskId)) {
        document.body.appendChild(maskElm);
      }
      target.style.cssText =
        "position:fixed;display:block;left:50%;top:50%;z-index:9999";
      target.style.marginLeft = "-" + target.offsetWidth / 2 + "px";
      target.style.marginTop = "-" + target.offsetHeight / 2 + "px";
      that.curTarget = target;
      $("#__cimi_dialog_mask")
        .off("click")
        .on("click", function() {
          cimi.dialog.close();
        });
    },
    close: function() {
      var maskElm = document.getElementById(this.maskId);
      if (maskElm) maskElm.parentNode.removeChild(maskElm);

      if (this.curTarget) {
        this.curTarget.style.display = "none";
        this.curTarget = null;
      }
    }
  }
};

MsiComm.init();
